import {UIElement, UIPanel} from "../../js/threejs/libs/ui.js";

export default class DeviceDetailData {
  // #colors = ['#1ad1ff', '#f356ff', '#97c12c', '#e9a173']
  #colors = ['#e3938f', '#62abd7', '#61a0a8', '#d48265',
    '#91c7ae', '#749f83', '#ca8622', '#86f15f', '#6e7074',
    '#3a97de', '#136dbc']

  #gaugeOption = {
    id: '',
    backgroundColor: 'rgb(24,41,69,0.5)',
    color: this.#colors,
    tooltip: {
      formatter: '{a}：{c}{b}',
      position: function (pos, params, dom, rect, size) {
        // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
        var obj = {top: pos[1]};
        obj[['left', 'right'][+(pos[0] >= size.viewSize[0] / 2)]] = pos[0];
        return obj;
      }
    },
    title: {
      text: '',
      fontWeight: 'bolder',
      fontSize: 20,
      fontStyle: 'italic',
      textStyle:{
        color: '#00fcff'
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {
          show:true,
          iconStyle: {
            borderColor: '#00fcff'
          }
        }
      }
    },
    series: [{
      name: '',
      type: 'gauge',
      detail: {
        formatter: '',
        borderRadius: 3,
        backgroundColor: 'rgba(27,60,116,0.5)',
        borderColor: '#1758a555',
        shadowBlur: 5,
        shadowColor: '#33333355',
        shadowOffsetX: 0,
        shadowOffsetY: 3,
        fontSize:18,
        color: '#00fcff',
      },
      data: [],
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 10,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 16,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
    }]
  };

  #lineOption = {
    id: '',
    backgroundColor: 'rgb(24,41,69,0.5)',
    color: this.#colors,
    title: {
      left: 'center',
      text: '',
      textStyle: {
        color: '#00fcff'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function (params) {
        let tip = ''
        params.forEach(param => tip += `${param.marker} ${param.data[0]} ${param.seriesName}：${param.data[1]} <br/>`)
        return tip
      },
    },
    toolbox: {
      feature: {
        dataZoom: {
          show: true,
          iconStyle: {
            borderColor: '#00fcff'
          }
        },
        restore: {
          show:true,
          iconStyle: {
            borderColor: '#00fcff'
          }
        },
        saveAsImage: {
          show:true,
          iconStyle: {
            borderColor: '#00fcff'
          }
        },
        magicType: {
          show:true,
          iconStyle: {
            borderColor: '#00fcff'
          },
          type: ["line", "bar"]
        },
      }
    },
    legend: {
      data: ['']
    },
    xAxis: [{
      name: '时间',
      type: 'time',
      axisLine: {
        lineStyle: {
          color: '#00fcff'
        }
      },
      splitLine: {
        show: false
      }
    }],
    yAxis: [{
      type: 'value',
      name: '',
      min: 0,
      max: 250,
      position: 'left',
      axisLabel: {
        formatter: '{value} ml'
      },
      splitLine: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: '#00fcff'
        }
      },
    }],
    dataZoom: [{
      type: 'slider',
      xAxisIndex: 0,
      filterMode: 'empty'
    },
      {
        type: 'slider',
        yAxisIndex: 0,
        filterMode: 'empty'
      }],
    series: [{
      name: '',
      type: 'line',
      symbolSize: 5,
      smooth: true,
      showSymbol: false,
      hoverAnimation: false,
      lineStyle: {
        color: ''
      },
      data: []
    }]
  }

  #sceneId

  constructor(displayer) {
    let scope = this

    let container = new UIPanel()
    container.dom.style.padding = '20px'
    container.dom.style.overflowY = 'auto'
    container.dom.style.height = `${displayer.VIEWPORT_HEIGHT - 35 - 40}px`
    container.dom.style.color = '#00fcff'
    container.dom.style.display = 'flex'
    container.dom.style.flexWrap = 'wrap'

    /* ----------------------------------------------------------------------------- */
    this.container = container

    displayer.signals.deployConfigLoaded.add(deployConfig => this.#sceneId = deployConfig.id)

    displayer.signals.deviceDetailed.add(object => {
      container.dom.innerHTML = ''
      displayer.request.getAction('/display/listHistoryReportData', {instanceId: object.uuid}).then((res) => {
        if (res.success) {
          /* 动态创建仪表盘 */
          scope.#createGaugeChart(res.result)
          /* 动态创建曲线图 */
          scope.#createLineChart(res.result)
          /* 动态创建曲线图 */
          scope.#createSwitchChart(res.result)
          /* 动态创建曲线图 */
            scope.#createMediaChart(res.result)
          }
        })
    })
    window.setTimeout(() => {
      displayer.signals.dataReceived.add(datas => {
        if (displayer.config.getKey('deviceDetailId')) {
          datas
            .filter(data => data.latestData['value'])
            .map(data => {
              DeviceDetailData.#updateGaugeChart(data)
              DeviceDetailData.#updateLineChart(data)
            })
        }
      })
    }, 500)


  }

  /**
   * 创建仪表图
   * @param datas
   */
  #createGaugeChart(datas) {
    let scope = this

    datas
      .filter(data => ('int、float、double'.indexOf(data.type) !== -1))
      .map(data => {
        scope.#gaugeOption.id = data.code
        scope.#gaugeOption.title.text = `${data.name}：${data.metadata['unit']}`
        scope.#gaugeOption.series[0].name = data.name
        scope.#gaugeOption.series[0].detail.formatter = `{value} ${data.metadata['unitSymbol']}`
        scope.#gaugeOption.tooltip.formatter =
          (params) => `设备名称：${data.instanceName}<br/>时间：${params.data.time}<br/>${data.name}：${params.value}${data.metadata['unitSymbol']}`
        scope.#gaugeOption.series[0].data = []
        if(data['historyDatas']){
          scope.#gaugeOption.series[0].data[0] = {
            value: data.historyDatas[data.historyDatas.length -1].value,
            time: data.historyDatas[data.historyDatas.length -1].reportTime
          }
        }else{
          scope.#gaugeOption.series[0].data[0] = {
            value: data.metadata.defaultValue,
            time: ''
          }
        }
        scope.#gaugeOption.series[0].min = data.metadata['minValue']
        scope.#gaugeOption.series[0].max = data.metadata['maxValue']

        let chartDom = document.getElementById(`panel-gauge-${data.instanceId}-${data.code}`.toString())
        let gaugePanel = new UIElement(chartDom)
        if(!gaugePanel.dom) {
          gaugePanel = new UIPanel()
          gaugePanel.setId(`panel-gauge-${data.instanceId}-${data.code}`.toString())
          gaugePanel.dom.style.width = '300px'
          gaugePanel.dom.style.height = '300px'
          gaugePanel.dom.style.margin = '10px'
          this.container.add(gaugePanel)
        }
        let chart = echarts.getInstanceByDom(gaugePanel.dom)
        if(!chart){
          chart = echarts.init(gaugePanel.dom)
        }
        chart.setOption({...scope.#gaugeOption})
      })
  }

  /**
   * 创建开关图
   * @param datas
   */
  #createSwitchChart(datas) {
    // 开关数据

    datas
      .filter(data => 'bool、int(0-1)'.indexOf(data.type) !== -1)
      .map(data => {


      })
  }

  #createLineChart(datas) {
    let scope = this
    datas
      .filter(data => 'int、float、double'.indexOf(data.type) !== -1)
      .map(data => {
        scope.#lineOption.id = data.code
        scope.#lineOption.title.text = `${data.name}：${data.metadata['unit']}`
        scope.#lineOption.yAxis[0].name = data.name + '(' + data.metadata['unit'] + ')'
        scope.#lineOption.yAxis[0].min = data.metadata['minValue']
        scope.#lineOption.yAxis[0].max = data.metadata['maxValue']
        scope.#lineOption.yAxis[0].axisLabel.formatter = '{value} ' + data.metadata['unitSymbol']
        scope.#lineOption.series[0].name = data.name
        scope.#lineOption.series[0].data = []
        if(data['historyDatas']) {
          scope.#lineOption.series[0].data = data.historyDatas.map(hisData => {
            return [
              hisData.reportTime,
              hisData.value
            ]
          })
        }

        let chartDom = document.getElementById(`panel-line-${data.instanceId}-${data.code}`.toString())
        let linePanel = new UIElement(chartDom)
        if(!linePanel.dom) {
          linePanel = new UIPanel()
          linePanel.setId(`panel-line-${data.instanceId}-${data.code}`)
          linePanel.dom.style.width = '1000px'
          linePanel.dom.style.height = '360px'
          linePanel.dom.style.margin = '10px'
          this.container.add(linePanel)
        }
        let chart = echarts.getInstanceByDom(linePanel.dom)
        if(!chart) {
          chart = echarts.init(linePanel.dom)
        }
        chart.setOption(JSON.parse(JSON.stringify(scope.#lineOption)))
      })


    // 仪表盘：int、float、double...数值型
    // 开关：bool、int(0-1)
    // 其它

    // 数据折线：int、float、double...数值型

  }

  #createMediaChart(datas) {
    let mediaPanel = new UIPanel()
    mediaPanel.dom.id = 'panel-media'
    mediaPanel.setClass = 'panel-media'
    this.container.add(mediaPanel)
  }

  static #updateGaugeChart(data) {
    // 仪表盘实时数据
    let chartDom = document.getElementById(`panel-gauge-${data.instanceId}-${data.code}`.toString())
    if (chartDom) {
      let chart = echarts.getInstanceByDom(chartDom)
      if (chart) {
        let option = chart.getOption()
        option.series[0].data[0] = {
          value: data.latestData.value,
          time: /\d\d:\d\d:\d\d/.exec(new Date(data.latestData.reportTime))
        }
        chart.setOption(option)
      }
    }
  }

  static #updateLineChart(data) {
    // 曲线实时数据
    let chartDom = document.getElementById(`panel-line-${data.instanceId}-${data.code}`.toString())
    if(chartDom) {
      let chart = echarts.getInstanceByDom(chartDom)
      if (chart) {
        let option = chart.getOption()
        let time = new Date(data.latestData.value).getTime() - new Date(option.series[0].data[0][0]).getTime()
        // 时间差大于一天时，删除最前的数据
        if (time >= 24 * 60 * 60 * 1000) {
          option.series[0].data.shift()
        }
        option.series[0].data.push([
          data.latestData.reportTime,
          data.latestData.value
        ])
        chart.setOption(option)
      }
    }
  }
}